package com.diyphonegadgets.yandroidcontroller.wifi;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class TCPClient implements Runnable {


	private String constructedJSONMessage(){
		
		
	  JSONObject object=new JSONObject();

  	  try {
		object.put("ServoValueLeft",GlobalData.leftY);
	  	object.put("ServoValueRight",GlobalData.rightY);

	} catch (JSONException e) {
		e.printStackTrace();
	}
  	  
  	    	
  	  System.out.println(object);
  	  
  	  return object.toString();
	}
	
	
    public synchronized void run() {
    	
    	
    	
    	
         try {
        	 
        	 InetAddress serverAddr = InetAddress.getByName(CommandManager.destinationIP);//TCPServer.SERVERIP
     
        	 
        	 
        	 String message = "";
        	 
        	 while(true){
        		 
        		 
        		 
        		if( GlobalData.leftActive || GlobalData.rightActive){
        		 
        		 Socket socket = new Socket(serverAddr, CommandManager.sendPort);
            	 
        	
        		 message=constructedJSONMessage();
        		 
        		 
        		 
        		 
        	 
		     try {
		    	// Log.d("TCP", "C: Sending: '" + message + "'");
		    	 PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
		    	 
		    	 out.println(message);
		    	 
             } catch(Exception e) {
                // Log.e("TCP", "S: Error", e);
		      }
        	 
             finally {
		        socket.close();
		      }
             
             
    		 Thread.sleep(CommandManager.updateInterval);

             
        	 }
         }
        	 
         }catch (Exception e) {
              Log.e("TCP", "C: Error", e);
         }
         
         
    }
}
